/**
 * @file
 * @brief This file implements a "very" simple sample client.
 * 
 * The client connects to the server, running at SERVERHOST:SERVERPORT
 * and performs a number of storage_* operations. If there are errors,
 * the client exists.
 */

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "storage.h"

#define SERVERHOST "localhost"
#define SERVERPORT 1111
#define SERVERUSERNAME "admin"
#define SERVERPASSWORD "dog4sale"
#define TABLE "marks"
#define KEY "ece297"


/**
 * @brief Start a client to interact with the storage server.
 *
 * If connect is successful, the client performs a storage_set/get() on
 * TABLE and KEY and outputs the results on stdout. Finally, it exists
 * after disconnecting from the server.
 */
int main(int argc, char *argv[]) {
  // Connect to server
  void *conn = storage_connect(SERVERHOST, SERVERPORT);
  if(!conn) {
    printf("Cannot connect to server @ %s:%d. Error code: %d.\n",
           SERVERHOST, SERVERPORT, errno);
    return -1;
  }

  // Authenticate the client.
  int status = storage_auth(SERVERUSERNAME, SERVERPASSWORD, conn);
  if(status != 0) {
    printf("storage_auth failed with username '%s' and password '%s'. " \
           "Error code: %d.\n", SERVERUSERNAME, SERVERPASSWORD, errno);
    storage_disconnect(conn);
    return status;
  }
  printf("storage_auth: successful.\n");

  // Issue storage_set
  struct storage_record r;
  strncpy(r.value, "some_value", sizeof r.value);
  status = storage_set(TABLE, KEY, &r, conn);
  if(status != 0) {
    printf("storage_set failed. Error code: %d.\n", errno);
    storage_disconnect(conn);
    return status;
  }
  printf("storage_set: successful.\n");

  // Issue storage_get
  status = storage_get(TABLE, KEY, &r, conn);
  if(status != 0) {
    printf("storage_get failed. Error code: %d.\n", errno);
    storage_disconnect(conn);
    return status;
  }
  printf("storage_get: the value returned for key '%s' is '%s'.\n",
         KEY, r.value);

  // Disconnect from server
  status = storage_disconnect(conn);
  if(status != 0) {
    printf("storage_disconnect failed. Error code: %d.\n", errno);
    return status;
  }

  // Exit
  return 0;
}
